package cn.kgc.springboot.shiro;

import cn.hutool.core.util.ObjectUtil;
import cn.kgc.springboot.entity.*;
import cn.kgc.springboot.service.*;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: mosin
 * @version: v1.0  2022/8/10
 */
public class CustomerRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private  UserRoleService  userRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePerService rolePerService;
    @Autowired
    private PermissionService permissionService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //获取用户的身份信息
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        User user = userService.selectByUserName(primaryPrincipal);
        //获取用户id  根据用户id 查询用户角色id
        Integer userId = user.getId();
        List<UserRole> userRoles = userRoleService.selectByUserId(userId);

        //用户角色id
        List<Integer> roleIds = userRoles.stream().map(userrole -> {
            return userrole.getRoleId();
        }).collect(Collectors.toList());
        //  根据用户身份信息 查询用户的角色信息
        List<String> roleNames = roleIds.stream().map(roleId -> {
            Role role = roleService.selectByRoleId(roleId);
            return role.getRoleName();
        }).collect(Collectors.toList());

        System.out.println("roleNames = " + roleNames);

        // 基于权限字符串授权

        // 根据用户角色id  查询角色权限id
        ArrayList<RolePer> rolePers = new ArrayList<>();
        roleIds.forEach(roleId->{
            rolePers.addAll(rolePerService.selectByRoleId(roleId));
        });

        //遍历rolePers 获取 权限id
        List<Integer> perIds = rolePers.stream().map(rolePer -> {
            return rolePer.getPerId();
        }).collect(Collectors.toList());

        // 根据权限id 查询权限的相信信息
        List<String> names = perIds.stream().map(perId -> {
            return permissionService.selectByPerId(perId).getName();
        }).filter(name->name!=null).collect(Collectors.toList());

        System.out.println("names = " + names);

        // 将用户的角色信息 进行授权操作
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleNames);
        simpleAuthorizationInfo.addStringPermissions(names);

        return simpleAuthorizationInfo;
    }


    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

       String principal = (String) token.getPrincipal();
        //  根据用户的身份信息  查询用户数据
        User user =  userService.selectByUserName(principal);
        System.out.println(user);
        // 判定用户是否存在
        if(ObjectUtil.isNotNull(user)){
             return  new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        }
        return null;
    }


}
